package com.lbd.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.lbd.common.to.SkuEsModel;
import com.lbd.common.utils.R;
import com.lbd.gulimall.search.config.ESConfig;
import com.lbd.gulimall.search.constant.EsConstant;
import com.lbd.gulimall.search.feign.ProductFeignService;
import com.lbd.gulimall.search.service.ElasticSearchService;
import com.lbd.gulimall.search.vo.AttrResponseVO;
import com.lbd.gulimall.search.vo.SearchParam;
import com.lbd.gulimall.search.vo.SearchResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.AbstractHighlighterBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.swing.text.Highlighter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: linbd
 * @Description:
 * @Date: 2023/2/11 11:55
 */
@Slf4j
@Service
public class ElasticSearchServiceImpl implements ElasticSearchService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private ProductFeignService productFeignService;

    @Override
    public boolean bulkIndexSkuModel(List<SkuEsModel> skuEsModels) throws IOException {
        BulkRequest bulkRequest = new BulkRequest(EsConstant.PRODUCT_INDEX);
        skuEsModels.forEach(skuEsModel -> {
            IndexRequest request = new IndexRequest();
            request.id(skuEsModel.getSkuId().toString());
            String data = JSON.toJSONString(skuEsModel);
            request.source(data, XContentType.JSON);
            bulkRequest.add(request);
        });
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, ESConfig.COMMON_OPTIONS);
        //true为有异常，false为正常
        boolean result = bulk.hasFailures();
        List<String> skuIds = Arrays.asList(bulk.getItems()).stream()
                .map(BulkItemResponse::getId).collect(Collectors.toList());
        log.info("上架的商品skuId => {}, 执行状态 => {}", skuIds, result);
        return !result;
    }

    @Override
    public SearchResult search(SearchParam param) {
        //构建DSL查询条件
        SearchRequest request = buildSearchRequest(param);
        try {
            //查询ES
            SearchResponse response = restHighLevelClient.search(request, ESConfig.COMMON_OPTIONS);
            //返回值封装
            return getSearchResult(response, param);
        } catch (IOException e) {
            log.error(e.getMessage());
            return null;
        }
    }

    /*
        keyword=小米&sort=saleCount_desc/asc&hasStock=0/1&skuPrice=400_1900&brandId=1&catalog3Id=1
        &attrs=1_3G:4G:5G&attrs=2_骁龙845&attrs=4_高清屏
    */
    private SearchRequest buildSearchRequest(SearchParam param) {
        SearchRequest request = new SearchRequest(EsConstant.PRODUCT_INDEX);
        SearchSourceBuilder builder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (!StringUtils.isEmpty(param.getKeyword())) {
            MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("skuTitle", param.getKeyword());
            boolQuery.must(matchQueryBuilder);

            //高亮
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            builder.highlighter(highlightBuilder);
        }
        if (param.getCatalog3Id() != null) {
            TermQueryBuilder catalogTermQuery = QueryBuilders.termQuery("catalogId", param.getCatalog3Id());
            boolQuery.filter(catalogTermQuery);
        }
        if (param.getBrandId() != null && param.getBrandId().size() > 0) {
            TermsQueryBuilder brandIdTermsQuery = QueryBuilders.termsQuery("brandId", param.getBrandId());
            boolQuery.filter(brandIdTermsQuery);
        }
        if (!StringUtils.isEmpty(param.getSkuPriceRange())) {
            RangeQueryBuilder skuPriceRangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String skuPriceRange = param.getSkuPriceRange();
            String[] split = skuPriceRange.split("_");
            if (skuPriceRange.startsWith("_")) {
                skuPriceRangeQuery.lt(split[1]);
            } else {
                if (split.length == 1) {
                    skuPriceRangeQuery.gt(split[0]);
                } else if (split.length == 2) {
                    skuPriceRangeQuery.gt(split[0]);
                    skuPriceRangeQuery.lt(split[1]);
                }
            }
            boolQuery.filter(skuPriceRangeQuery);
        }
        if (param.getHasStock() != null) {
            TermQueryBuilder hasStockTermQuery = QueryBuilders.termQuery("hasStock", param.getHasStock() == 1);
            boolQuery.filter(hasStockTermQuery);
        }
        // attrs=1_3G:4G:5G & attrs=2_骁龙845 & attrs=4_高清屏
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            for (String attr : param.getAttrs()) {
                BoolQueryBuilder attrsNestedBoolQuery = QueryBuilders.boolQuery();
                String[] split = attr.split("_");
                String attrId = split[0];
                String[] attrValues = split[1].split(":");
                attrsNestedBoolQuery.filter(QueryBuilders.termQuery("attrs.attrId", attrId));
                attrsNestedBoolQuery.filter(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                NestedQueryBuilder attrsNestedQuery = QueryBuilders.nestedQuery("attrs", attrsNestedBoolQuery, ScoreMode.None);
                boolQuery.filter(attrsNestedQuery);
            }
        }
        builder.query(boolQuery);
        //排序
        String sort = param.getSort();
        if (!StringUtils.isEmpty(sort)) {
            String[] split = sort.split("_");
            SortOrder order = "asc".equals(split[1]) ? SortOrder.ASC : SortOrder.DESC;
            builder.sort(split[0], order);
        }
        //分页
        builder.from((param.getPageNum() - 1) * EsConstant.PAGE_SIZE);
        builder.size(EsConstant.PAGE_SIZE);
        //聚合
        //品牌汇聚
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brand_agg").field("brandId").size(30);
        TermsAggregationBuilder brandNameAgg = AggregationBuilders.terms("brand_name_agg").field("brandName").size(1);
        brandAgg.subAggregation(brandNameAgg);
        TermsAggregationBuilder brandImgAgg = AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1);
        brandAgg.subAggregation(brandImgAgg);
        builder.aggregation(brandAgg);
        //分类汇聚
        TermsAggregationBuilder categoryAgg = AggregationBuilders.terms("category_agg").field("catalogId").size(30);
        TermsAggregationBuilder categoryNameAgg = AggregationBuilders.terms("category_name_agg").field("catalogName").size(1);
        categoryAgg.subAggregation(categoryNameAgg);
        builder.aggregation(categoryAgg);
        //属性汇聚
        NestedAggregationBuilder attrNestedAgg = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(10);
        attrNestedAgg.subAggregation(attrIdAgg);
        TermsAggregationBuilder attrNameAgg = AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1);
        attrIdAgg.subAggregation(attrNameAgg);
        TermsAggregationBuilder attrValueAgg = AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(15);
        attrIdAgg.subAggregation(attrValueAgg);
        builder.aggregation(attrNestedAgg);
        request.source(builder);
        return request;
    }

    private SearchResult getSearchResult(SearchResponse response, SearchParam param) {
        SearchHits hits = response.getHits();
        SearchResult result = new SearchResult();
        //设置sku商品基本信息
        List<SkuEsModel> products = new ArrayList<>();
        for (SearchHit hit : hits.getHits()) {
            String productJsonStr = hit.getSourceAsString();
            SkuEsModel skuEsModel = JSON.parseObject(productJsonStr, SkuEsModel.class);
            //高亮字段重设
            if (!StringUtils.isEmpty(param.getKeyword())) {
                Map<String, HighlightField> highlightFieldsMap = hit.getHighlightFields();
                HighlightField skuTitleHighlightField = highlightFieldsMap.get("skuTitle");
                Text text = skuTitleHighlightField.getFragments()[0];
                skuEsModel.setSkuTitle(text.toString());
            }
            products.add(skuEsModel);
        }
        result.setProducts(products);
        //分页信息
        int totalNum = (int) hits.getTotalHits().value;
        result.setPageNum(param.getPageNum());
        int totalPageNum = totalNum % EsConstant.PAGE_SIZE == 0 ? totalNum / EsConstant.PAGE_SIZE : (totalNum / EsConstant.PAGE_SIZE) + 1;
        result.setTotalPageNum(totalPageNum);
        result.setTotalNum(totalNum);
        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= totalPageNum; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);

        //设置涉及信息
        Aggregations aggregations = response.getAggregations();
        //品牌涉及
        ParsedLongTerms brandAgg = aggregations.get("brand_agg");
        List<SearchResult.BrandRespVO> brandRespVOS = new ArrayList<>();
        for (Terms.Bucket bucket : brandAgg.getBuckets()) {
            SearchResult.BrandRespVO brandRespVO = new SearchResult.BrandRespVO();
            Long brandId = (Long) bucket.getKey();
            Aggregations brandSubAggregations = bucket.getAggregations();
            ParsedStringTerms brandNameAgg = brandSubAggregations.get("brand_name_agg");
            String brandName = String.valueOf(brandNameAgg.getBuckets().get(0).getKey());
            ParsedStringTerms brandImgAgg = brandSubAggregations.get("brand_img_agg");
            String brandImg = String.valueOf(brandImgAgg.getBuckets().get(0).getKey());
            brandRespVO.setBrandId(brandId);
            brandRespVO.setBrandName(brandName);
            brandRespVO.setBrandImg(brandImg);
            brandRespVOS.add(brandRespVO);
        }
        result.setInvolveBrands(brandRespVOS);
        //分类涉及
        ParsedLongTerms categoryAgg = aggregations.get("category_agg");
        List<SearchResult.CategoryRespVO> categoryRespVOS = new ArrayList<>();
        for (Terms.Bucket bucket : categoryAgg.getBuckets()) {
            SearchResult.CategoryRespVO categoryRespVO = new SearchResult.CategoryRespVO();
            Long catalogId = (Long) bucket.getKey();
            Aggregations categorySubAggregations = bucket.getAggregations();
            ParsedStringTerms categoryNameAgg = categorySubAggregations.get("category_name_agg");
            String categoryName = String.valueOf(categoryNameAgg.getBuckets().get(0).getKey());
            categoryRespVO.setCatalogId(catalogId);
            categoryRespVO.setCatalogName(categoryName);
            categoryRespVOS.add(categoryRespVO);
        }
        result.setInvolveCategorys(categoryRespVOS);
        //属性涉及
        ParsedNested attrAgg = aggregations.get("attr_agg");
        Aggregations attrAggSubAggregations = attrAgg.getAggregations();
        ParsedLongTerms attrIdAgg = attrAggSubAggregations.get("attr_id_agg");
        List<? extends Terms.Bucket> buckets = attrIdAgg.getBuckets();
        List<SearchResult.AttrRespVO> attrRespVOS = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            SearchResult.AttrRespVO attrRespVO = new SearchResult.AttrRespVO();
            Long attrId = (Long) bucket.getKey();
            Aggregations attrIdSubAggregations = bucket.getAggregations();
            ParsedStringTerms attrNameAgg = attrIdSubAggregations.get("attr_name_agg");
            String attrName = String.valueOf(attrNameAgg.getBuckets().get(0).getKey());
            ParsedStringTerms attrValueAgg = attrIdSubAggregations.get("attr_value_agg");
            List<? extends Terms.Bucket> attrValueBuckets = attrValueAgg.getBuckets();
            List<String> attrValues = new ArrayList<>();
            for (Terms.Bucket attrValueBucket : attrValueBuckets) {
                String attrValue = String.valueOf(attrValueBucket.getKey());
                attrValues.add(attrValue);
            }
            attrRespVO.setAttrId(attrId);
            attrRespVO.setAttrName(attrName);
            attrRespVO.setAttrValues(attrValues);
            attrRespVOS.add(attrRespVO);
        }
        result.setInvolveAttrs(attrRespVOS);

        //设置面包屑导航的数据
        List<SearchResult.NavVo> navVos = new ArrayList<>();
        //品牌
        if (param.getBrandId() != null && param.getBrandId().size() > 0) {
            List<SearchResult.NavVo> brandNavVos = param.getBrandId().stream().map(curBrandId -> {
                //一个品牌id对应一个名称
                String brandName = result.getInvolveBrands().stream()
                        .filter(brandInfo -> brandInfo.getBrandId().equals(curBrandId)) //包装类数值大于127不能用==比较值
                        .map(SearchResult.BrandRespVO::getBrandName)
                        .collect(Collectors.toList()).get(0);
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                navVo.setAttrName("品牌");
                navVo.setAttrValue(brandName);

                String encode = null;
                try {
                    //Request中获取的请求参数是URL编码后的。由于这个地址要回传前端，所以选择将attr进行编码兼容。如果将请求参数解码处理，前端将会出问题
                    encode = URLEncoder.encode(String.valueOf(curBrandId), "UTF-8").replace("+", "%20");//浏览器对空格编码为“%20”，java编码为“+”。这里要进行特殊处理
                    //删除面包屑，应该保存一份删除了当前的attrs请求参数的地址，供前端进行跳转
                    String line = param.get_qStr().replace("&brandId=" + encode, "");
                    navVo.setLink("http://search.gulimall.com/list.html?" + line);
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
                return navVo;
            }).collect(Collectors.toList());
            navVos.addAll(brandNavVos);
        }

        //分类
        if (param.getCatalog3Id() != null) {
            Long catalog3Id = param.getCatalog3Id();
            String catalogName = result.getInvolveCategorys().stream()
                    .filter(categoryInfo -> categoryInfo.getCatalogId().equals(catalog3Id))
                    .map(SearchResult.CategoryRespVO::getCatalogName)
                    .collect(Collectors.toList()).get(0);
            SearchResult.NavVo navVo = new SearchResult.NavVo();
            navVo.setAttrName("分类");
            navVo.setAttrValue(catalogName);
            navVo.setLink("http://search.gulimall.com/list.html?" + param.get_qStr());
            List<SearchResult.NavVo> categoryNavVos = new ArrayList<>();
            categoryNavVos.add(navVo);
            navVos.addAll(categoryNavVos);
        }
        List<Long> selectedAttrIds = new ArrayList<>();
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            List<SearchResult.NavVo> attrNavVos = param.getAttrs().stream().map(attr -> {
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                String[] split = attr.split("_");
                String attrValues = split[1];
                navVo.setAttrValue(attrValues);
                //调用商品微服务获取属性名
                String attrId = split[0];
                selectedAttrIds.add(Long.valueOf(attrId));
                //远程调用耗时，可通过缓存远程方法降低耗时
                R r = productFeignService.info(Long.valueOf(attrId));
                if (r.getCode() == 0) {
                    AttrResponseVO attrInfo = r.getData("attr", new TypeReference<AttrResponseVO>() {
                    });
                    String attrName = attrInfo.getAttrName();
                    navVo.setAttrName(attrName);
                } else {
                    navVo.setAttrName(attrId);
                }
                String encode = null;
                try {
                    //Request中获取的请求参数是URL编码后的。由于这个地址要回传前端，所以选择将attr进行编码兼容。如果将请求参数解码处理，前端将会出问题
                    encode = URLEncoder.encode(attr, "UTF-8").replace("+", "%20");//浏览器对空格编码为“%20”，java编码为“+”。这里要进行特殊处理
                    //删除面包屑，应该保存一份删除了当前的attrs请求参数的地址，供前端进行跳转
                    String line = param.get_qStr().replace("&attrs=" + encode, "");
                    navVo.setLink("http://search.gulimall.com/list.html?" + line);
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
                return navVo;
            }).collect(Collectors.toList());
            navVos.addAll(attrNavVos);
            //log.info("面包屑信息：{}", navVos);
        }
        result.setNavVos(navVos);
        log.info("已选择属性id：{}",selectedAttrIds);
        result.setSelectedAttrIds(selectedAttrIds);
        return result;
    }
}
